package cn.xunjie.basic.service.impl;

import cn.xunjie.basic.dto.RegisterDto;
import cn.xunjie.basic.exception.BusinessException;
import cn.xunjie.basic.service.IVerifyCodeService;
import cn.xunjie.basic.util.StrUtils;
import cn.xunjie.basic.util.VerifyCodeUtils;
import cn.xunjie.user.domain.User;
import cn.xunjie.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @Override
    public String imageCode(String key) {
        //判断key是否为空
        if(!StringUtils.hasLength(key)){
            throw new BusinessException("不可以搞黄色哦");
        }
        //调用工具包随机产生4位数的随机数
        String code = StrUtils.getComplexRandomString(4);
        //设置过期时间
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        return VerifyCodeUtils.VerifyCode(100,40,code);


    }

    @Override
    public void smsCode(RegisterDto dto) {


   /* registerSmsCode(dto);
}else if("binder".equals(type)){//绑定短信验证码
        binderSmsCode(dto);*/
        String type = dto.getType();
        if(StringUtils.isEmpty(type)){
            throw new BusinessException("type不能为空");

        }
        if("register".equals(type)){
            registerSmsCode(dto);
        }else if ("binder".equals(type)){
            binderSmsCode(dto);
        }
    }

    private void binderSmsCode(RegisterDto dto) {
        /*sendSmsCode(businessKey);*/
        String businessKey = "BaseConstant.RegisterConstants.BINDER_SMS_PREFIX"+dto.getPhone();
        sendSmsCode(businessKey);
    }

    private void sendSmsCode(String businessKey) {
        String key = businessKey;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        String smsCode = "";
        if(smsCodeTmp!=null){
            Long aLong = Long.valueOf(smsCodeTmp.toString().split(":")[1]);
            if(System.currentTimeMillis()-aLong <= 60*1000){
                throw new BusinessException("你在搞事？");
            }
            smsCode = smsCodeTmp.toString().split(":")[0];
        }else {
            smsCode = StrUtils.getRandomString(4);
        }
        String smsCodeValue = smsCode + ":" + System.currentTimeMillis();

        //3.存储redis 设置一个过期时间
        redisTemplate.opsForValue().set(
                key,
                smsCodeValue,
                3,
                TimeUnit.MINUTES
        );

        // 4.发送短信
        /*SmsUtils.sendSms(phone,"亲，您的验证码是："+smsCode+"。请在3分钟内使用！！");*/
        System.out.println("亲，您的验证码是：" + smsCode + "。请在3分钟内使用！！");
    }



    public void registerSmsCode(RegisterDto dto){
            String imageCodeKey = dto.getImageCodeKey();
            String imageCodeValue = dto.getImageCodeValue();
            String phone = dto.getPhone();
            //1.空校验
            if(StringUtils.isEmpty(imageCodeKey) || StringUtils.isEmpty(imageCodeValue) || StringUtils.isEmpty(phone)){
                throw new BusinessException("参数不能为空");
            }
            //2.校验图形验证码，根据imageCodeKey从redis获取图像验证码
            Object imageCodeTmp = redisTemplate.opsForValue().get(imageCodeKey);
            //.获取不到 图像验证码过期
            if(imageCodeTmp == null){
                throw new BusinessException("验证码过期请重新获取");
            }
            //获取到了对比图行验证码是否正确 对比不要区分大小写
            if(!imageCodeTmp.toString().equalsIgnoreCase(imageCodeValue)){
                throw new BusinessException("验证码不正确请重新输入");
            }
            //正确往下做
            //3.校验手机号是否注册过
            User user = userService.queryByphone(phone);

            //。注册过了，过回去登录
            if(user!=null){
                throw new BusinessException("你已经注册过了，请登录");
            }

            //。没有注册，往下做
            //1.根据手机号拼接key，159:register；从redis获取曾今可能发送的短信验证码

            String key = "register:" + phone;
            Object smsCodeTmp = redisTemplate.opsForValue().get(key);
            //1.1 获取到了
            String smsCode = "";
            if(smsCodeTmp != null){
                // 1.1.1 校验是否过了一分钟重发时间 value
                Long oldTime = Long.valueOf(smsCodeTmp.toString().split(":")[1]);
                //。小于一分钟  哥屋恩
                if(System.currentTimeMillis()-oldTime <= 60*1000){
                    throw new BusinessException("你他妈的不要乱搞");
                }
                //。大于一分中 （还没有到3分钟，验证码还有效）
                smsCode = smsCodeTmp.toString().split(":")[0];



            }else {
                //使用还没过期的验证码，刷新过期时间
                //1.2 获取不到
                //1.2.1.生成新的短信验证码
                smsCode = StrUtils.getRandomString(4);
            }
            String smsCodeValue = smsCode + ":" + System.currentTimeMillis();

            //3.存储redis 设置一个过期时间
            redisTemplate.opsForValue().set(
                    key,
                    smsCodeValue,
                    3,
                    TimeUnit.MINUTES
            );

            // 4.发送短信
            /*SmsUtils.sendSms(phone,"亲，您的验证码是："+smsCode+"。请在3分钟内使用！！");*/
            System.out.println("亲，您的验证码是：" + smsCode + "。请在3分钟内使用！！");
        }
    }

